<template>
  <div class="app-container">
    <!--上层 计划情况和公告-->
    <el-row :gutter="10">

      <el-col :span="17" v-loading="indexLoading">
        <div class="welcome-box">
          <span class="welcome-word">Welcome, {{ username }}</span>
          <span class="motto">{{ getCurrMotto }}</span>
          <el-button size="medium" type="text" icon="el-icon-refresh" @click="handleNextMotto" />
        </div>

        <ul class="statistic-box">
          <li v-for="(item,index) in statisticResults" :key="index">
            <!--            图标-->
            <div class="icon-box son-box"
                 :style="statisticStyles[index].style"
            >
              <img :src="statisticStyles[index].icon" alt="" />
            </div>
            <!--            内容-->
            <div class="content-box son-box">
              <el-statistic
                group-separator=","
                :value="item.count"
                :title="item.name"
              />
            </div>
          </li>
        </ul>

        <!--        工作量-->
        <div class="my-echarts-box">
          <div id="task-statistic" class="box-border" ref="task-statistic" v-loading="echartsLoading">
          </div>
          <div class="my-tool-box">
            <div>
              <el-button
                size="mini"
                type="text"
                @click="updateEcharts(7)"
              >
                最近7天
              </el-button>
            </div>
            <div>
              <el-button
                size="mini"
                type="text"
                @click="updateEcharts(30)"
              >
                最近30天
              </el-button>
            </div>
            <div>
              <el-button
                size="mini"
                type="text"
                @click="updateEcharts(365)"
              >
                最近1年
              </el-button>
            </div>
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="box-border">
                <div class="drawback-box" ref="drawback-box" v-loading="drawbackLoading"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="box-border">
                <div class="procedure-box" ref="procedure-box" v-loading="procedureLoading"></div>
              </div>
            </el-col>
          </el-row>
        </div>

      </el-col>

      <el-col :span="7">
        <div class="quick-box">
          <MyCard title="快速发起">
            <template slot="content">
              <div class="quick-son-list">
                <div class="quick-son" v-for="item in quickStartRes" :key="item.href">
                  <el-link type="primary" :href="item.href" :underline="false">
                    <div class="quick-son-icon">
                      <img :src="item.src" alt="" class="quick-son-icon-src">
                    </div>
                    <div class="quick-son-title">
                      {{ item.title }}
                    </div>
                  </el-link>
                </div>
              </div>
            </template>

          </MyCard>
        </div>

        <!--        预警box-->
        <div class="alert-box">
          <MyCard title="预警信息" />
        </div>

        <!--        notice box-->
        <div class="notice-box">
          <el-tabs v-model="noticeName" @tab-click="handleClickNoticeTab">
            <el-tab-pane label="通知" name="1" />
            <el-tab-pane label="公告" name="2" />
          </el-tabs>
          <el-table v-loading="noticeLoading" :data="noticeList" style="height: 220px;max-height: 220px">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-descriptions :column="2" direction="vertical">
                  <el-descriptions-item label="内容">{{ scope.row.noticeContent }}</el-descriptions-item>
                </el-descriptions>
              </template>
            </el-table-column>
            <el-table-column
              label="标题"
              align="center"
              prop="noticeTitle"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="发布时间" align="center" prop="createTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="noticeTotal > 1"
            :total="noticeTotal"
            :page.sync="noticeQueryParams.pageNum"
            :limit.sync="noticeQueryParams.pageSize"
            @pagination="getNoticeList"
          />
        </div>

      </el-col>
    </el-row>

    <!--    下层 生产进度-->

  </div>
</template>

<script>
import * as echarts from 'echarts/core'
import { GridComponent, LegendComponent, TitleComponent, ToolboxComponent, TooltipComponent } from 'echarts/components'
import { BarChart, PieChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'

import user from '../store/modules/user'
import { listNotice } from '@/api/system/notice'
import { getDateResult, listBadProcedure, listDrawbackRange, listIndex } from '@/api/yyj/index'
import MyCard from '@/components/MyCard/index.vue'
import { background } from 'quill/ui/icons'

export default {
  name: 'Index',
  components: { MyCard },
  data() {
    return {
      indexLoading: true,
      echartsLoading: true,
      // 统计结果个数
      statisticResults: [],
      statisticStyles: [
        {
          icon: require('@/assets/icons/svg/index-schedule.png'),
          style: {
            backgroundColor: 'rgb(0,153,255)'
          }
        }, {
          icon: require('@/assets/icons/svg/index-order.png'),
          style: {
            backgroundColor: 'rgb(251, 98, 96)'
          }
        }, {
          icon: require('@/assets/icons/svg/index-task.png'),
          style: {
            backgroundColor: 'rgb(255,169, 76)'
          }
        }, {
          icon: require('@/assets/icons/svg/index-report.png'),
          style: {
            backgroundColor: 'rgb(81,211, 81)'
          }
        }, {
          icon: require('@/assets/icons/svg/index-quality.png'),
          style: {
            backgroundColor: 'rgb(123, 99,234)'
          }
        }
      ],
      // charts
      myCharts: {},
      // opt 数据
      opt: {
        title: {
          show: true,
          text: '任务统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            interval: '1'
          }
        ],
        series: [
          {
            name: '任务开工数量',
            type: 'bar',
            barWidth: '60%',
            data: []
          }
        ]
      },
      // drawbackECharts
      drawbackCharts: {},
      // drawbackLoading: true,
      drawbackLoading: true,
      // drawbackOpt 数据
      drawbackOpt: {
        title: {
          show: true,
          text: '缺陷占比'
        },
        tooltip: {
          trigger: 'item'
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            saveAsImage: { show: true }
          }
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: []
      },
      // procedureECharts
      procedureCharts: {},
      // procedureLoading
      procedureLoading: true,
      //
      procedureOpt: {
        title: {
          show: true,
          text: '不合格工序分布'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            saveAsImage: { show: true }
          }
        }
      },
      // notice 加载
      noticeLoading: true,
      // 公告信息
      noticeList: [],
      // notice 查询参数
      noticeQueryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeType: '1'
      },
      // notice 总数
      noticeTotal: 0,
      // 当前选中的tab
      noticeName: '1',
      // 所有的motto
      mottos: [
        '虽然工作是累人的，但想想每个月的薪水，你会发现自己是最贵的奴隶！',
        '闪烁的灯光是我在异世界大声地呼唤你。',
        '长生非我愿，但求达慕垂鞭。'
      ],
      // 当前motto下标
      currentMottoIndex: 0,
      // 快速发起
      quickStartRes: [
        {
          title: '生产计划',
          href: '/pro/schedule',
          src: require('@/assets/icons/png/index-schedule.png')
        }, {
          title: '生产工单',
          href: '/pro/workOrder',
          src: require('@/assets/icons/png/index-order.png')
        }, {
          title: '工单任务',
          href: '/pro/workTask',
          src: require('@/assets/icons/png/index-task.png')
        }, {
          title: '报工质检',
          href: '/pro/workReport',
          src: require('@/assets/icons/png/index-report.png')
        }
      ]
    }
  },
  computed: {
    background() {
      return background
    },
    username() {
      return user.state.name
    },
    getCurrMotto() {
      if (!this.mottos[this.currentMottoIndex]) {
        this.currentMottoIndex = 0
      }
      return this.mottos[this.currentMottoIndex]
    }
  },
  created() {
    echarts.use([TitleComponent, TooltipComponent, GridComponent, BarChart, CanvasRenderer, LegendComponent, PieChart, ToolboxComponent])
    Promise.all([this.getNoticeList(), this.getTotals()])
  },
  mounted() {
    this.myCharts = echarts.init(this.$refs['task-statistic'])
    this.drawbackCharts = echarts.init(this.$refs['drawback-box'])
    this.procedureCharts = echarts.init(this.$refs['procedure-box'])
    Promise.all([this.updateEcharts(7), this.updateDrawbackRangeEcharts(), this.updateBadProcedureECharts()])
  },
  methods: {
    // 获取下一个motto
    handleNextMotto() {
      this.currentMottoIndex++
    },
    // 获取 pro 数量
    async getTotals() {
      this.indexLoading = true
      const res = await listIndex()
      res.data = res.data.map(e => {
        return {
          name: e.name,
          count: parseInt(e.count)
        }
      })
      this.statisticResults = res.data
      this.indexLoading = false
    },
    // 获取 notice
    async getNoticeList() {
      this.noticeLoading = true
      const res = await listNotice(this.noticeQueryParams)
      this.noticeList = res.rows
      this.noticeTotal = res.total
      this.noticeLoading = false
    },
    // 点击 notice tab
    handleClickNoticeTab(tab) {
      this.noticeQueryParams.noticeType = tab.name
      this.getNoticeList()
    },
    // 更新 echarts 数据
    async updateEcharts(date) {
      this.echartsLoading = true
      const res = await getDateResult(date)
      this.opt.xAxis = [
        {
          type: 'category',
          data: res.data.map(e => e.date),
          axisTick: {
            alignWithLabel: true
          }
        }
      ]
      this.opt.series = [
        {
          name: '任务开工数量',
          type: 'bar',
          barWidth: '60%',
          data: res.data.map(e => e.count),
          itemStyle: {
            // 为每个柱子设置不同的颜色
            color: () => this.generateWarmColor()
          }
        }
      ]
      this.myCharts.setOption(this.opt)
      this.echartsLoading = false
    },
    // 更新 drawbackRange 数据
    async updateDrawbackRangeEcharts() {
      this.drawbackLoading = true
      const res = await listDrawbackRange()
      this.drawbackOpt.series = [
        {
          name: '缺陷统计',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
            // 为每个柱子设置不同的颜色
            color: () => this.generateWarmColor()
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 24,
              fontWeight: 'normal'
            }
          },
          labelLine: {
            show: false
          },
          data: res.data.map(e => {
            return {
              name: e.name,
              value: e.count
            }
          })
        }
      ]
      this.drawbackCharts.setOption(this.drawbackOpt)
      this.drawbackLoading = false
    },
    // 获取不合格工序
    async updateBadProcedureECharts() {
      this.procedureLoading = true
      const res = await listBadProcedure()
      this.procedureOpt.series = [
        {
          name: '不合格工序',
          type: 'pie',
          radius: '75%',
          center: ['50%', '50%'],
          itemStyle: {
            // 为每个柱子设置不同的颜色
            color: () => this.generateWarmColor()
          },
          data: res.data.map(e => {
            return {
              name: e.name,
              value: e.count
            }
          })
        }
      ]
      this.procedureCharts.setOption(this.procedureOpt)
      this.procedureLoading = false
    },
    // 随机颜色
    generateWarmColor() {
      let hue = Math.floor(Math.random() * 360) // 随机生成色相值，范围为0-359

      // 排除黑色、灰色、棕色等难看的颜色
      if (hue >= 0 && hue <= 30) {
        hue += 30 // 使生成的颜色偏向红色调
      } else if (hue >= 150 && hue <= 210) {
        hue += 60 // 使生成的颜色偏向黄色调
      }

      const saturation = Math.floor(Math.random() * 50) + 50 // 随机生成饱和度值，范围为50-100
      const lightness = Math.floor(Math.random() * 20) + 60 // 随机生成亮度值，范围为60-80

      return `hsl(${hue}, ${saturation}%, ${lightness}%)`
    }

  }
}
</script>

<style scoped lang="scss">
li {
  list-style: none;
}

.welcome-box {
  .welcome-word {
    font-weight: bolder;
    font-size: 20px;
  }

  .motto {
    margin-left: 10px;
    color: rgba(0, 0, 0, 0.647058823529412);
  }
}

.statistic-box {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;

  .son-box {
    margin: 0 10px;
  }

  li {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 25%;

    .icon-box {
      position: relative;
      width: 50px;
      height: 50px;
      text-align: center;
      vertical-align: middle;
      border-radius: 50%;

      img {
        position: absolute;
        width: 40px;
        height: 40px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}

.my-echarts-box {
  position: relative;

  #task-statistic {
    width: 100%;
    height: 400px;
    margin-bottom: 20px;
    margin-top: 20px;
  }

  .my-tool-box {
    display: flex;
    position: absolute;
    top: 5px;
    right: 10px;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 50px;

    div {
      padding: 0 2px;
    }
  }

  .box-border {
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    background-color: #FFFFFF;
    overflow: hidden;
    color: #303133;
    -webkit-transition: 0.3s;
    transition: 0.3s;
  }
}

.drawback-box {
  height: 300px;
}

.procedure-box {
  height: 300px;
}

.quick-box {
  width: 100%;
  height: auto;
  margin-bottom: 20px;

  .quick-son-list {
    display: flex;
    justify-content: space-between;
    align-content: space-between;
    flex-wrap: wrap;
    padding: 0 5%;
    width: 100%;

    .quick-son {
      width: calc(90% / 4);
      text-align: center;
      margin-bottom: 5px;

      .quick-son-icon {
        width: 50px;
        height: 50px;
        margin: 0 auto;

        .quick-son-icon-src {
          width: 100%;
          height: 100%;
        }
      }

      .quick-son-title {
        margin-top: 10px;
        margin-bottom: 10px;
        color: #606266;
      }
    }
  }
}

.alert-box {
  width: 100%;
  margin-bottom: 20px;
}

.notice-box {
  width: 100%;
}
</style>

